package com.bh.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.uuid.IdUtils;
import com.bh.wms.domain.WmsStocktakeDetail;
import com.bh.wms.domain.WmsStocktakeOrder;
import com.bh.wms.mapper.WmsStocktakeDetailMapper;
import com.bh.wms.mapper.WmsStocktakeOrderMapper;
import com.bh.wms.service.IWmsStocktakeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 盘点单服务实现
 *
 * @author GPT
 */
@Service
public class WmsStocktakeOrderServiceImpl extends ServiceImpl<WmsStocktakeOrderMapper, WmsStocktakeOrder> implements IWmsStocktakeOrderService {

    private static final String DEFAULT_STATUS = "created";

    @Autowired
    private WmsStocktakeDetailMapper stocktakeDetailMapper;

    @Override
    public WmsStocktakeOrder selectWmsStocktakeOrderById(Long id) {
        WmsStocktakeOrder order = baseMapper.selectById(id);
        if (order != null) {
            List<WmsStocktakeDetail> details = stocktakeDetailMapper.selectList(new LambdaQueryWrapper<WmsStocktakeDetail>()
                    .eq(WmsStocktakeDetail::getStocktakeOrderId, id)
                    .orderByAsc(WmsStocktakeDetail::getId));
            order.setDetails(details);
        }
        return order;
    }

    @Override
    public List<WmsStocktakeOrder> selectWmsStocktakeOrderList(WmsStocktakeOrder query) {
        LambdaQueryWrapper<WmsStocktakeOrder> wrapper = new LambdaQueryWrapper<>();
        if (query != null) {
            if (StringUtils.isNotEmpty(query.getOrderNo())) {
                wrapper.eq(WmsStocktakeOrder::getOrderNo, query.getOrderNo());
            }
            if (StringUtils.isNotEmpty(query.getStocktakeType())) {
                wrapper.eq(WmsStocktakeOrder::getStocktakeType, query.getStocktakeType());
            }
            if (query.getWarehouseId() != null) {
                wrapper.eq(WmsStocktakeOrder::getWarehouseId, query.getWarehouseId());
            }
            if (StringUtils.isNotEmpty(query.getOrderStatus())) {
                wrapper.eq(WmsStocktakeOrder::getOrderStatus, query.getOrderStatus());
            }
        }
        wrapper.orderByDesc(WmsStocktakeOrder::getCreateTime);
        return baseMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertWmsStocktakeOrder(WmsStocktakeOrder entity) {
        fillCreateInfo(entity);
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            entity.setOrderNo(buildStocktakeNo());
        }
        if (StringUtils.isEmpty(entity.getOrderStatus())) {
            entity.setOrderStatus(DEFAULT_STATUS);
        }
        int rows = baseMapper.insert(entity);
        saveDetailList(entity, true);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateWmsStocktakeOrder(WmsStocktakeOrder entity) {
        fillUpdateInfo(entity);
        int rows = baseMapper.updateById(entity);
        saveDetailList(entity, true);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWmsStocktakeOrderByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        for (Long id : ids) {
            removeDetails(id);
        }
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWmsStocktakeOrderById(Long id) {
        removeDetails(id);
        return baseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(WmsStocktakeOrder entity) {
        fillUpdateInfo(entity);
        return baseMapper.updateById(entity);
    }

    private void saveDetailList(WmsStocktakeOrder entity, boolean cleanBefore) {
        if (entity == null || entity.getId() == null) {
            return;
        }
        if (cleanBefore) {
            removeDetails(entity.getId());
        }
        if (CollectionUtils.isEmpty(entity.getDetails())) {
            return;
        }
        Date now = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        for (WmsStocktakeDetail detail : entity.getDetails()) {
            detail.setStocktakeOrderId(entity.getId());
            if (detail.getStatus() == null) {
                detail.setStatus(1);
            }
            detail.setCreateName(username);
            detail.setCreateTime(now);
            detail.setModifyName(username);
            detail.setModifyTime(now);
            if (detail.getDiffQuantity() == null && detail.getBookQuantity() != null && detail.getCountQuantity() != null) {
                detail.setDiffQuantity(detail.getCountQuantity() - detail.getBookQuantity());
            }
            stocktakeDetailMapper.insert(detail);
        }
    }

    private void removeDetails(Long orderId) {
        stocktakeDetailMapper.delete(new LambdaQueryWrapper<WmsStocktakeDetail>().eq(WmsStocktakeDetail::getStocktakeOrderId, orderId));
    }

    private void fillCreateInfo(WmsStocktakeOrder entity) {
        Date now = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        if (entity.getStatus() == null) {
            entity.setStatus(1);
        }
        entity.setCreateName(username);
        entity.setCreateTime(now);
        entity.setModifyName(username);
        entity.setModifyTime(now);
    }

    private void fillUpdateInfo(WmsStocktakeOrder entity) {
        entity.setModifyName(SecurityUtils.getUsername());
        entity.setModifyTime(DateUtils.getNowDate());
    }

    private String buildStocktakeNo() {
        return "ST" + DateUtils.dateTimeNow() + (IdUtils.getSnowNextId() % 1000);
    }
}

